package com.axa.mule.transformer;

import java.io.IOException;
import java.io.InputStream;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.mule.api.transformer.TransformerException;
import org.mule.config.i18n.MessageFactory;
import org.mule.transformer.AbstractTransformer;

import com.axa.sms.portal.Msg;
import com.axa.sms.portal.Msglist;
import com.axa.sms.portal.ObjectFactory;

public class HSSF2MsglistTransformer extends AbstractTransformer {
	Logger logger = Logger.getLogger(HSSF2MsglistTransformer.class);
	
	@Override
	protected Object doTransform(Object src, String enc)
			throws TransformerException {
		ObjectFactory of = new ObjectFactory();
		Msglist msglist = of.createMsglist();
		
		HSSFWorkbook wb = null;
		try {
			wb = new HSSFWorkbook((InputStream) src);
		} catch (IOException e) {
			
			logger.error("HSSF2SMSListTransformer error while getting stream. "+ e.getMessage());
			
			throw new TransformerException(MessageFactory.createStaticMessage("error while getting stream: "+ e.getMessage()), this);
		}
		Sheet sheet = wb.getSheetAt(wb.getActiveSheetIndex());
		int rows = sheet.getPhysicalNumberOfRows();
		logger.info("HSSF2SMSListTransformer: rows = "+ rows);
		
		for (int r = 0; r < rows; r++) {
			Row row = sheet.getRow(r);
			if (row == null) {
				msglist.getMsg().add(of.createMsg());
				continue;
			}
			
			Msg msg = of.createMsg();
			Cell cell = null;
			
			/* phone number */
			cell = row.getCell(1);
			msg.setAddr(getAsString(cell));
			
			/* client name */
			cell = row.getCell(0);
			msg.setRecipient(getAsString(cell));
			
			/* msg text */
			cell = row.getCell(2);
			msg.setValue(getAsString(cell));
			
			/* msg id */
			cell = row.getCell(3);
			msg.setId(getAsString(cell));
			
			/* sender == department */
			cell = row.getCell(4);
			msg.setSender(getAsString(cell));
						
			msglist.getMsg().add(msg);
		}
		return msglist;
	}
	
	private String getAsString(Cell cell) {
		String value;
		
		if (cell == null){
			return "";
		}
		
		final int celltype = cell.getCellType();
		switch (celltype) {
			case Cell.CELL_TYPE_STRING:  value = cell.getStringCellValue();					 break;
			case Cell.CELL_TYPE_BOOLEAN: value = String.valueOf(cell.getBooleanCellValue()); break;
			case Cell.CELL_TYPE_NUMERIC: value = String.valueOf(cell.getNumericCellValue()); break;
			default: 					 value = "";
		}
		
		return value;
	}
}
